I'm attempting to create a user profile page that generates content based on the current tab the user is in.
The tab is decided based on what is passed in the URL (e.g. /username/tab1). The only issue with this is that one of the valid tabs the user can visit actually has a blank value (/username, to get the default tab).
However, when you enter this into the browser, Next automatically assumes I want to retrieve /[user]/index.js (which doesn't exist), when in actuality what I want to get is /[user]/[tab].js and pass a blank value to the tab property in context.query.
Is this possible without creating a separate index.js and [tab].js file?
// Exported inside /pages/[user]/[tab].js
export const getServerSideProps = async (context) => {
const { page, tab } = context.query;
// When we're on /username/foo it should output "foo".
// When we're on /username it should output "".
console.log(tab);
};
You can achieve this using an optional catch-all route.
So, rename your [tab].js as [[...tab]].js, so it will catch also the requests to /username without a tab. Then in your code you'll handle tab as optional.